package com.example.pei.ithinklearnt.present;

import android.content.Context;
import android.content.Intent;
import android.view.inputmethod.InputMethodManager;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.bean.AlumniCircle;
import com.example.pei.ithinklearnt.bean.Comment;
import com.example.pei.ithinklearnt.bean.AddCommentMessage;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.model.AlumniCircleModel;
import com.example.pei.ithinklearnt.model.AlumniCircleModelImp;
import com.example.pei.ithinklearnt.model.CommentModel;
import com.example.pei.ithinklearnt.model.CommentModelImp;
import com.example.pei.ithinklearnt.model.PraiseModel;
import com.example.pei.ithinklearnt.model.PraiseModelImp;
import com.example.pei.ithinklearnt.utils.DialogUtil;
import com.example.pei.ithinklearnt.utils.ToastUtil;
import com.example.pei.ithinklearnt.view.interfaces.DynamicDetailsInterface;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static android.app.Activity.RESULT_OK;

import static com.example.pei.ithinklearnt.utils.DialogUtil.CreateVerifyDialog;

public class DynamicDetailsPresentImp implements DynamicDetailsPresent {

    private DynamicDetailsInterface dynamicDetailsInterface;
    private CommentModel commentModel;
    private AlumniCircleModel alumniCircleModel;
    private PraiseModel praiseModel;

    private UserInfo currentUser;

    private int commentNum;     //当前动态的评论数量
    private int praiseNum;      //当前动态的点赞个数

    private KProgressHUD hud; //等待进度条

    public DynamicDetailsPresentImp(DynamicDetailsInterface dynamicDetailsInterface){
        this.dynamicDetailsInterface=dynamicDetailsInterface;
        this.commentModel=new CommentModelImp();
        this.alumniCircleModel=new AlumniCircleModelImp();
        this.praiseModel=new PraiseModelImp();
        currentUser=AppApplication.getCurrentUser();

    }

    @Override
    public void initDynamicCommentAndPraiseNum(int comment, int praise) {
        this.commentNum=comment;
        this.praiseNum=praise;
    }

    @Override
    public void sendComment(final Comment coment) {

        dynamicDetailsInterface.btn_sendCommentClickable(false);

        //查询这个动态是否被删除
       alumniCircleModel.findAlumniCircleByObjectId(coment.getDynamic().getObjectId(), new AlumniCircleModelImp.findAlumniCircle() {
           @Override
           public void success(AlumniCircle object) {
               if(object!=null){

                   //动态还在，可以评论
                   coment.save(new SaveListener<String>() {
                       @Override
                       public void done(String s, BmobException e) {
                           if(e==null){
                               dynamicDetailsInterface.getAdapter().addComment(coment);
                               dynamicDetailsInterface.clearEditText();  //清空输入框
                               dynamicDetailsInterface.btn_sendCommentClickable(true);
                               //详情页面设置评论数量+1
                               commentNum++;
                               dynamicDetailsInterface.setCommentNumer(commentNum);

                               //发送回复提醒
                               sendCommentRemind(coment, new SaveListener<Object>() {
                                   @Override
                                   public void done(Object o, BmobException e) {

                                   }
                               });
                               //尝试更新服务器中动态的评论数量，未成功也可以纠正
                               alumniCircleModel.addOneComment(coment.getDynamic().getObjectId(), new AlumniCircleModelImp.addOneComment() {
                                   @Override public void succeed() {}
                                   @Override public void failed() {}
                               });

                           }else{
                               dynamicDetailsInterface.btn_sendCommentClickable(true);
                               ToastUtil.ToastShow(dynamicDetailsInterface.getActivity(),"评论失败",0);
                           }
                       }
                   });



               }else{
                   dynamicDetailsInterface.btn_sendCommentClickable(true);
               }


           }

           @Override
           public void failed(BmobException e) {
               dynamicDetailsInterface.btn_sendCommentClickable(true);
               SweetAlertDialog dialog=new SweetAlertDialog(dynamicDetailsInterface.getActivity(), SweetAlertDialog.ERROR_TYPE);
               dialog.setTitleText("唉哟...");
               if(e.getErrorCode()==101){
                   dialog.setContentText("这条主题突然消失了~")
                           .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                               @Override
                               public void onClick(SweetAlertDialog sweetAlertDialog) {
                                   Intent intent = new Intent();
                                   intent.putExtra("key", "miss");
                                   dynamicDetailsInterface.getActivity().setResult(RESULT_OK, intent);
                                   dynamicDetailsInterface.getActivity().finish();
                               }
                           });

               }else if(e.getErrorCode()==9016){
                   dialog.setContentText("网络跑丢了~");
               }else {
                   dialog.setContentText("发生了莫名其妙的错误~");
               }
                dialog.show();
           }
       });


        // 隐藏输入法，然后暂存当前输入框的内容，方便下次使用
        InputMethodManager im = (InputMethodManager) AppApplication.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        assert im != null;
        im.hideSoftInputFromWindow(dynamicDetailsInterface.getActivity().findViewById(R.id.et_content).getWindowToken(), 0);

    }



    @Override
    public void deleteComment(final String commentObjectId,final String alumniCircleId,final int position) {

        CreateVerifyDialog(dynamicDetailsInterface.getActivity(),"确认删除这条评论吗?",new DialogUtil.CreateVerifyDialogListener(){
            @Override
            public void confirm() {
                hud = KProgressHUD.create(dynamicDetailsInterface.getActivity())
                        .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                        .setDimAmount(0.4f)
                        .setLabel("正在删除...")
                        .setCornerRadius(10)
                        .show();

                commentModel.deleteComment(commentObjectId, new CommentModelImp.deleteCommentListener() {
                    @Override
                    public void succeed() {
                        dynamicDetailsInterface.getAdapter().deleteComment(position-1);
                        dynamicDetailsInterface.getAdapter().notifyDataSetChanged();
                        dynamicDetailsInterface.setCommentNumer(dynamicDetailsInterface.getAdapter().getCount());
                        hud.dismiss();
                        //动态中记录的评论数量减一，但失败了也无所谓
                        alumniCircleModel.deleteComment(alumniCircleId, new AlumniCircleModelImp.deleteOneComment() {
                            @Override public void succeed() {}
                            @Override public void failed() {}
                        });
                    }

                    @Override
                    public void failed() {
                        ToastUtil.ToastShow(dynamicDetailsInterface.getActivity(),"删除失败",0);
                        hud.dismiss();
                    }
                });
            }

            @Override
            public void cancel() {

            }
        });
    }

    //发送评论的提醒
    private void  sendCommentRemind(final Comment coment,final SaveListener<Object> listener){
        if (BmobIM.getInstance().getCurrentStatus().getCode() != ConnectionStatus.CONNECTED.getCode()) {
            ToastUtil.ToastShow(AppApplication.getContext(),"尚未连接IM服务器",0);
            return;
        }
        final UserInfo currentUser = BmobUser.getCurrentUser(UserInfo.class);
        //构造发送对象的信息
        UserInfo u=coment.getUserTo();
        if(u.getObjectId().equals(currentUser.getObjectId())){
            //自己评论自己的动态，不需要发送消息
            return;
        }
        BmobIMUserInfo info = new BmobIMUserInfo(u.getObjectId(), u.getUsername(), u.getHeadFileUrl());
        //会话：4.1、创建一个暂态会话入口，发送评论提醒
        BmobIMConversation conversationEntrance = BmobIM.getInstance().startPrivateConversation(info, true, null);
        //消息：5.1、根据会话入口获取消息管理，发送评论提醒
        BmobIMConversation messageManager = BmobIMConversation.obtain(BmobIMClient.getInstance(), conversationEntrance);
        //而AgreeAddFriendMessage的isTransient设置为false，表明我希望在对方的会话数据库中保存该类型的消息
        AddCommentMessage msg = new AddCommentMessage();

        msg.setContent(currentUser.getNickName() + "回复了你的内容"+coment.getBcontent());//这句话是直接存储到对方的消息表中的

        Map<String, Object> map = new HashMap<>();
        map.put("id",coment.getObjectId());                //这条回复的objectId
        map.put("content", coment.getContent());//回复的内容

        if(coment.getBcontent()==null||coment.getBcontent().equals("")){
            //回复的是动态
            if(coment.getDynamic().getContent()==null||coment.getDynamic().getContent().equals("")){
                //发表的是图片动态，没有文字
                map.put("bcontent","我:[图片]");
            }else{
                map.put("bcontent","我:"+coment.getDynamic().getContent());
            }

        }else{
            //回复的是评论
            map.put("bcontent","我:"+coment.getBcontent());
        }

        map.put("name", currentUser.getNickName());       //回复者的用户名
        map.put("avator",currentUser.getHeadFileUrl());   //回复者的头像
        msg.setExtraMap(map);
        messageManager.sendMessage(msg, new MessageSendListener() {
            @Override
            public void done(BmobIMMessage msg, BmobException e) {
                if (e == null) {//发送成功
                  //  NewFriendManager.getInstance(dynamicDetailsInterface.getActivity()).updateNewFriend(add, Config.STATUS_VERIFIED);
                    listener.done(msg, e);
                } else {//发送失败
                    listener.done(msg, e);
                }
            }
        });
    }

    @Override
    public void queryHeader(String objectId) {



        alumniCircleModel.findAlumniCircleByObjectId(objectId, new AlumniCircleModelImp.findAlumniCircle() {
            @Override
            public void success(AlumniCircle object) {
                dynamicDetailsInterface.setPraiseNumber(object.getPraiseNumber());
            }

            @Override
            public void failed(BmobException e) {
                if (e.getErrorCode() == 101) {
                    new SweetAlertDialog(dynamicDetailsInterface.getActivity(), SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("唉哟...")
                            .setContentText("这条主题突然消失了~")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    Intent intent = new Intent();
                                    intent.putExtra("key", "miss");
                                    dynamicDetailsInterface.getActivity().setResult(RESULT_OK, intent);
                                    dynamicDetailsInterface.getActivity().finish();
                                }
                            }) .show();
                }


            }
        });
    }

    @Override
    public void queryComments(final AlumniCircle al) {


        //下载动态objectid 的所有评论
        commentModel.queryComments(al, new CommentModelImp.queryComentsListener() {
            @Override
            public void queryComentsSucceed(List<Comment> results) {
                //先清空适配器的comments
                dynamicDetailsInterface.getAdapter().clearComment();
                for(Comment comment:results ){
                    //将comment添加到适配器
                    if(comment.getDynamic()!=null){  //存在这个动态
                        dynamicDetailsInterface.getAdapter().addComment(comment);
                    }
                }
                //更新Header中评论数量
                dynamicDetailsInterface.setCommentNumer(results.size());
                //如果服务器中的评论数量不正确，应该纠正
                if(results.size()!=commentNum){
                    AlumniCircle alumniCircle  = new AlumniCircle();
                    alumniCircle.setCommentNumber(results.size());
                    alumniCircle.update(al.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {

                        }
                    });
                }

                //设置刷新成功
                dynamicDetailsInterface.refreshFinish(true);
            }
            @Override
            public void queryComentsFailed() {
                //设置刷新失败
                dynamicDetailsInterface.refreshFinish(false);
            }
        });



    }

    @Override
    public void shieldAlumniCircle(String userName,String objectId) {
        alumniCircleModel.shieldAlumniCircle(userName, objectId, new AlumniCircleModelImp.shieldAlumniCircle() {
            @Override
            public void succeed() {
                Intent intent = new Intent();
                intent.putExtra("key", "shield");
                dynamicDetailsInterface.getActivity().setResult(RESULT_OK, intent);
                dynamicDetailsInterface.getActivity().finish();
            }
            @Override
            public void failed() {
                ToastUtil.ToastShow(dynamicDetailsInterface.getActivity(),"不好意思，屏蔽失败了...",0);
            }
        });
    }

    @Override
    public void praiseAlumniCircle(String userName,String objectId) {
        //服务器上查看是否从未点赞状态变成改变状态
        praiseModel.praiseAlumniCircle(currentUser.getUsername(), objectId,
                new PraiseModelImp.praiseAlumniCircle() {
                    @Override
                    public void becomePraised() {
                        //未点赞状态变成点赞状态
                        dynamicDetailsInterface.setPraised();
                    }
                });
        //服务器中点赞数量加一
        alumniCircleModel.addOneLike(objectId);
        //Header
        praiseNum++;
        dynamicDetailsInterface.setPraiseNumber(praiseNum);
    }

    @Override
    public void deleteAlumniCircle(AlumniCircle al,List photoUrls) {
        hud = KProgressHUD.create(dynamicDetailsInterface.getActivity())
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setDimAmount(0.4f)
                .setLabel("正在删除...")
                .setCornerRadius(10)
                .show();

        alumniCircleModel.deleteAlumniCircle(al, photoUrls, new AlumniCircleModelImp.deleteAlumniCircle() {
            @Override
            public void succeed() {
                Intent intent = new Intent();
                intent.putExtra("key", "delete");
                dynamicDetailsInterface.getActivity().setResult(RESULT_OK, intent);
                dynamicDetailsInterface.getActivity().finish();
                hud.dismiss();
            }

            @Override
            public void failed() {
                ToastUtil.ToastShow(dynamicDetailsInterface.getActivity(),"不好意思，删除失败了...",0);
                hud.dismiss();
            }
        });
    }






}
